const fs = require('fs');
const path = require('path');
var tools = require('../../../libs/tools');
var config = require(tools.rootPath + 'config');
var { connection, pool, model } = require(tools.rootPath + 'libs/model');

var controller = require(tools.rootPath + 'libs/controller.js');

var WechatAPI = require('co-wechat-api');
var api = new WechatAPI('wx00edea76e8cf692c', 'd2db4eaeff4824dc50929ba50218b776', async function () {
    // 传入一个获取全局token的方法
    var txt = fs.readFileSync(tools.runtimePath + 'access_token.txt', 'utf8');
    return JSON.parse(txt);
}, async function (token) {
    // 请将token存储到全局，跨进程、跨机器级别的全局，比如写到数据库、redis等
    // 这样才能在cluster模式及多机情况下使用，以下为写入到文件的示例
    fs.writeFileSync(tools.runtimePath + 'access_token.txt', JSON.stringify(token));
});

var OAuth = require('co-wechat-oauth');
var client = new OAuth('wx00edea76e8cf692c', 'd2db4eaeff4824dc50929ba50218b776');

var _ = require('lodash');

module.exports = class extends controller {
    constructor() {
        super();

    }
    //自动回复地址
    //http://szh.vaiwan.com/wechat
    //Token验证
    //https://blog.csdn.net/logan_LG/article/details/105915857
    async index(req, res, next) {
        //const { signature, nonce, timestamp, echostr } = req.query;
        //console.log(echostr);
        //res.end(echostr);
        //return;

    }
    //发送模板消息
    async send_template(req, res) {
        var templateId = 'n3ihOOsyzAFpgVXzkhxKtyiaZ7C3s56ZEVm7O-WvFsc';
        // URL置空，则在发送后,点击模板消息会进入一个空白页面（ios）, 或无法点击（android）
        var url = 'https://www.baidu.com';
        var topColor = '#FF0000'; // 顶部颜色
        var data = {
            title: {
                "value": 'hello!',
                "color": "#173177"
            },
            content: {
                "value": 'good day!',
                "color": "#173177"
            }

        };
        var result = await api.sendTemplate('oajSN5pnT1WyA9DdDJ_JE7vASN1M', templateId, url, topColor, data);
        console.log(result);
        res.end('ok');
    }
    //oauth
    async login(req, res) {
        var url = client.getAuthorizeURL('http://szh2021.free.idcfengye.com/index/wechat/callback', 'state', 'snsapi_userinfo');
        res.render(req.TPL, { url: url });
    }
    //callback
    async callback(req, res) {
        let code = req.query.code;
        let state = req.query.state;
        if (!code) {
            res.end('');
            return;
        }

        var token = await client.getAccessToken(code);
        var accessToken = token.data.access_token;
        var openid = token.data.openid;
        var userInfo = await client.getUser(openid);
        req.session.USER = userInfo;

        /*
{
  openid: 'oajSN5pnT1WyA9DdDJ_JE7vASN1M',
  nickname: '不忘初心',
  sex: 1,
  language: 'zh_CN',
  city: '',
  province: '',
  country: 'Ecuador',
  headimgurl: 'http://thirdwx.qlogo.cn/mmopen/vi_32/d0aVgo6YAsq7iciavnibxKM3bhnWuQicO5stkLxwJqXdMnF7a3dWao0zxCYibjOiagjbgXaic4YjiaPsOPBsXXwH8Zjgdw/132',
  privilege: []
}
        */

        console.log(userInfo);
        res.redirect('/index/wechat/home');
    }
    async home(req, res) {
        if (!req.session.USER) {
            res.redirect('/index/wechat/login');
            return;
        }
        let USER = req.session.USER;

        let { ticket } = await api.createTmpQRCode(10000, 1800);
        let url = api.showQRCodeURL(ticket);

        res.render(req.TPL, { USER: USER, url: url });
    }
    async logout(req, res) {
        delete req.session.USER;
        res.redirect('/index/wechat/login');
    }
    //https://developers.weixin.qq.com/doc/offiaccount/Custom_Menus/Creating_Custom-Defined_Menu.html
    async menu(req, res) {
        function make_item(a, b, c) {
            if (!a.length) return false;
            let sub_button = _.zipWith(b, c, (name, url) => {
                return {
                    type: 'view',
                    name: name,
                    url: url,
                };
            });
            sub_button = sub_button.filter((elemnet) => {
                return elemnet.name.length > 0 && elemnet.url.length > 0;
            });
            if (!sub_button.length) return false;
            return {
                name: a,
                sub_button: sub_button,
            };
        }
        let menu_file = tools.rootPath + 'menu.json';
        if (req.ispost) {
            let data = req.body;
            delete data.submit;
            let r = true;
            try {
                await fs.promises.writeFile(menu_file, JSON.stringify(data));
            } catch (err) {
                if (err) r = false;
            }
            if (r) {
                let menu = {
                    button: [

                    ]
                };
                let first = make_item(data.a[0], data.name.slice(0, 5), data.url.slice(0, 5));
                if (first !== false) menu.button.push(first);
                let second = make_item(data.a[1], data.name.slice(5, 10), data.url.slice(5, 10));
                if (second !== false) menu.button.push(second);
                let third = make_item(data.a[2], data.name.slice(10, 15), data.url.slice(10, 15));
                if (third !== false) menu.button.push(third);
                if (menu.button.length > 0) {
                    let result = await api.createMenu(menu);
                    console.log(result);
                    //{ errcode: 0, errmsg: 'ok' }
                }

            }
            res.send(tools.msg(r));
            return;
        }
        let data = null;
        try {
            data = fs.readFileSync(menu_file);
        } catch (err) {
            if (err) data = '{"a":[],"name":[],"url":[]}';
        }
        data = JSON.parse(data);
        res.render(req.TPL, { ...data });
    }
}